<template>
    <section>
        <full-screen-dialog
            :title="handleType==3?'查看':''+handleType==2?'编辑申请':''+handleType==1?'进行对账':''"
            v-model="visible"
            :width="1500"
            destroy-on-close
            @closed="$emit('closed')"
        >
            <el-form ref="dialogForm" label-width="100px">
                <el-form
                    inline
                    label-width="49px"
                    :model="entityObj"
                    style="margin-top: 5px"
                >
                    <el-form-item label="对账时间" label-width="100px">
                        <el-date-picker
                            style="width: 300px"
                            v-model="entityObj.accountDate"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                        />
                    </el-form-item>
                    <el-form-item label="客户名称" label-width="100px">
                        <sc-store-select
                            disabled
                            ref="orgselect"
                            :props="storeProps"
                            :selectKeyValue="'storeId'"
                            v-model="entityObj.store"
                            :multiple="false"
                            @fatherMethod="orgSelectProcess"
                            style="width: 100%;"
                        ></sc-store-select>
                    </el-form-item>
                    <br />
                    <el-form-item label="申请人" label-width="100px">
                        <el-input
                            placeholder="---请输入申请人---"
                            v-model="entityObj.applicantUser"
                            style="width: 300px"
                            :disabled="handleType=='1'"
                        />
                    </el-form-item>
                    <el-form-item label="联系电话" label-width="100px">
                        <el-input
                            placeholder="---请输入联系电话---"
                            v-model="entityObj.tel"
                            style="width: 300px"
                            :disabled="handleType=='1'"
                        />
                    </el-form-item>
                    <br />
                    <el-form-item label-width="120px" label="附件上传">
                        <sc-upload-file
                            style="width: 300px"
                            v-model="entityObj.accountFile"
                            :objName="'Supply/giveOrder'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                            :disabled="handleType=='1'"
                        />
                    </el-form-item>
                    <el-form-item
                        label="对账申请单位"
                        label-width="100px"
                    >{{entityObj.purchaseUnityFullName}}</el-form-item>
                    <br />
                    <el-form-item label="备注" label-width="120px">
                        <el-input
                            placeholder="---请输入一些对账的要求---"
                            v-model="entityObj.remarks"
                            type="textarea"
                            style="width: 300px"
                        />
                    </el-form-item>
                </el-form>
                <div style="margin-bottom: 10px;">
                    <el-button
                        v-if="handleType==='2'||handleType==='1'"
                        @click="opDelSelect"
                        type="primary"
                    >批量删除</el-button>
                    <el-button v-if="handleType==='1'" type="primary" @click="allSelect()">批量已对账</el-button>
                    <el-button
                        v-if="handleType==='2'||handleType==='1'"
                        type="primary"
                        @click="openBIgTable()"
                    >选择出库单</el-button>
                </div>
                <el-form inline label-width="49px" style="margin-top: 5px">
                    <el-form-item label="物料编号" label-width="80px">
                        <el-input
                            placeholder="---请输入编号---"
                            v-model="queryList.materialCode"
                            style="width: 160px"
                        />
                    </el-form-item>
                    <el-form-item label="物料名称" label-width="80px">
                        <el-input
                            placeholder="---请输入名称---"
                            v-model="queryList.materialName"
                            style="width: 160px"
                        />
                    </el-form-item>
                    <el-form-item label="物料规格" label-width="80px">
                        <el-input
                            placeholder="---请输入规格---"
                            v-model="queryList.materialSpecs"
                            style="width: 160px"
                        />
                    </el-form-item>
                    <el-form-item label="关联单号" label-width="80px">
                        <el-input
                            placeholder="---请输入关联单号---"
                            v-model="queryList.applyOrderCode"
                            style="width: 160px"
                        />
                    </el-form-item>
                    <el-form-item label-width="80px">
                        <el-button
                            :icon="Search"
                             
                            type="primary"
                            @click="handleSearch"
                        >查询</el-button>
                        <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                    </el-form-item>
                </el-form>
                <el-table
                    :data="entityObj.items"
                    :row-class-name="setRowClass"
                    :border="true"
                    style="width: 100%;height: 400px;"
                    @selection-change="handleSelectionChange"
                    show-summary
                    :summary-method="getSummaries"
                >
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column label="序号" type="index" width="60"></el-table-column>
                    <el-table-column label="业务日期" width="130" prop="applyDate">
                        <template
                            #default="scope"
                        >{{ scope.row.applyDate.length>10? scope.row.applyDate.slice(0, 10):scope.row.applyDate}}</template>
                    </el-table-column>

                    <el-table-column label="物料名称" width="200" prop="materialName"></el-table-column>
                    <el-table-column label="规格型号" width="100" prop="materialSpecs"></el-table-column>
                    <el-table-column label="单位" width="80" prop="unitName"></el-table-column>
                    <el-table-column label="结算数量" prop="qty" width="90"></el-table-column>
                    <!-- <el-table-column prop="deliveryQty" width="70">
						<template #header>
							<el-popover placement="top-start" :width="200" trigger="hover" content="收货数量,退货数量,空瓶有效数量">
								<template #reference>
									数量
								</template>
							</el-popover>
						</template>
					</el-table-column>
                    <el-table-column label="差异数量" width="90" prop="lackQty"></el-table-column>-->
                    <el-table-column label="结算价" width="100" prop="price"></el-table-column>
                    <!-- <el-table-column label="要货单价" width="100" prop="applyPrice"></el-table-column>
                    <el-table-column label="差异价格" width="100" prop="lackPrice"></el-table-column>-->
                    <el-table-column label="结算金额" width="100" prop="totalAmount"></el-table-column>
                    <el-table-column label="备注" prop="remarks" width="180">
                        <template #default="scope">
                            <el-input
                                placeholder="---请输入备注---"
                                v-model="scope.row.remarks"
                                style="width: 100%"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="单据编号" width="200" prop="orderCode"></el-table-column>
                    <el-table-column label="客户" width="250" prop="storeName"></el-table-column>
                    <el-table-column label="类型" width="150">
                        <!-- <template #default="scope">
						{{scope.row.receivingOrderType=='0'?'销售出库单':''}}
						{{scope.row.receivingOrderType=='1'?'销售退货单':''}}
						{{scope.row.receivingOrderType=='2'?'销售回瓶单':''}}
						{{scope.row.receivingOrderType=='3'?'销售赠送单':''}}
                        </template>-->
                        <template #default="scope">
                            {{scope.row.receivingOrderType=='0'?'要货订单':''}}
                            {{scope.row.receivingOrderType=='1'?'退货订单':''}}
                            {{scope.row.receivingOrderType=='2'?'空瓶订单':''}}
                            {{scope.row.receivingOrderType=='3'?'赠送订单':''}}
                        </template>
                    </el-table-column>
                    <el-table-column label="对账人" width="120" prop="reviewed"></el-table-column>
                    <el-table-column label="制单人" width="120" prop="documentsUser"></el-table-column>
                    <el-table-column label="关联单号" width="150" prop="applyOrderCode"></el-table-column>

                    <!-- <el-table-column label="配送数量" prop="deliveryQty" width="150"></el-table-column> -->
                    <el-table-column label="物料编码" width="100" prop="materialCode"></el-table-column>
                    <el-table-column v-if="orgType=='1'" label="对账状态" width="100">
                        <template #default="scope">
                            {{scope.row.reconciliationStatus=='1'?'对账正确':''}}
                            {{scope.row.reconciliationStatus=='2'?'未对账':''}}
                            {{scope.row.reconciliationStatus=='3'?'对账中':''}}
                            {{scope.row.reconciliationStatus=='4'?'已发送申请':''}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        v-if="orgType=='2'"
                        label="对账状态"
                        width="130"
                        prop="reconciliationStatusName"
                    >
                        <template #default="scope">
                            {{scope.row.storeReconciliationStatus=='1'?'对账正确':''}}
                            {{scope.row.storeReconciliationStatus=='2'?'未对账':''}}
                            {{scope.row.storeReconciliationStatus=='3'?'对账中':''}}
                            {{scope.row.storeReconciliationStatus=='4'?'已接收申请':''}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        v-if="orgType=='1'"
                        label="操作"
                        fixed="right"
                        align="center"
                        width="200"
                    >
                        <template #default="scope">
                            <el-button-group>
                                <el-button
                                    v-if="handleType==='2'||handleType==='1'"
                                    text
                                    type="primary"
                                    size="small"
                                    @click="opDel(scope.row, scope.$index)"
                                >删除</el-button>
                                <el-button
                                    v-if="handleType==='1' && (scope.row.storeReconciliationStatus == '2'||scope.row.reconciliationStatus == '3'||scope.row.reconciliationStatus == '4')"
                                    text
                                    type="primary"
                                    size="small"
                                    @click="opSelect(scope.row, scope.$index)"
                                >对账正确</el-button>
                                <el-button
                                    v-if="handleType!='3' && scope.row.reconciliationStatus!='1'"
                                    text
                                    type="primary"
                                    size="small"
                                    @click="opCheck(scope.row, scope.$index)"
                                >核对</el-button>
                                <div v-if="handleType==='3'">-</div>
                            </el-button-group>
                        </template>
                    </el-table-column>
                    <el-table-column
                        v-if="orgType=='2'"
                        label="操作"
                        fixed="right"
                        align="center"
                        width="150"
                    >
                        <template #default="scope">
                            <el-button-group>
                                <el-button
                                    v-if="handleType==='2'"
                                    text
                                    type="primary"
                                    size="small"
                                    @click="opDel(scope.row, scope.$index)"
                                >删除</el-button>
                                <el-button
                                    v-if="handleType==='1' && (scope.row.storeReconciliationStatus == '2'||scope.row.storeReconciliationStatus == '3'||scope.row.storeReconciliationStatus == '4')"
                                    text
                                    type="primary"
                                    size="small"
                                    @click="opSelect(scope.row, scope.$index)"
                                >对账正确</el-button>
                                <div v-if="handleType==='3'">-</div>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <template #footer>
                <div style="text-align: center;">
                    <el-button @click="visible = false">关 闭</el-button>
                    <el-button v-if="handleType==='1'" type="primary" @click="visible = false">确认</el-button>
                    <el-button
                        v-if="handleType==='2'||handleType==='1'"
                        type="primary"
                        @click="isSaveing(0)"
                    >保存</el-button>
                </div>
            </template>
        </full-screen-dialog>

        <!-- 选择出库单 list -->
        <receive-big
            v-if="visibleBig"
            ref="visibleBig"
            @checkTable="checkTable"
            @success="handleSaveSuccess"
            @closed="visibleBig = false"
        ></receive-big>

        <!-- 核对弹窗 -->
        <check-dialog
            v-if="dialogCheck"
            ref="checkDialog"
            @success="handleSaveSuccess"
            @fatherMethod="checkSaveSuccess"
            @closed="dialogCheck = false"
        ></check-dialog>

        <!-- 要货价格修改 -->
        <update-price-dialog
            v-if="dialogUpdatePrice"
            ref="updatePriceDialog"
            @fatherMethod="opBindData"
            @success="handleSaveSuccess"
            @closed="dialogUpdatePrice = false"
        ></update-price-dialog>
    </section>
</template>

<script>
import updatePriceDialog from "../../apply/order/updatePrice.vue";
import checkDialog from "./check";
import receiveBig from "./receiveBig";
import tool from "@/utils/tool";
export default {
    components: {
        receiveBig,
        checkDialog,
        updatePriceDialog,
    },
    emits: ["success", "closed"],
    data() {
        return {
            columnIndex: "",
            storeProps: {
                label: "storeName",
                value: "storeId",
            },
            dialogCheck: false,
            visibleBig: false,
            dialogUpdatePrice:false,
            visible: false,
            // 发送请求的实体modal
            entityObj: {
                salesAccountID: 0,
                storeId: "",
                accountFile: "",
                accountDate: [],
                items: [],
                store: "",
                purchaseUnityFullName: "",
            },
            queryList: {},
            initItems: [], // 初始化存储
            handleType: "", // 查看/编辑
            multipleSelection: [], // 勾选中的列表
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
        };
    },
    methods: {
        openBIgTable() {
            this.visibleBig = true;
            this.$nextTick(() => {
                console.log("opBigTable", this.entityObj.items);
                this.$refs.visibleBig.initData(
                    this.entityObj.items,
                    this.entityObj.storeId
                );
            });
        },
        setRowClass({ row }) {
            if (this.multipleSelection.includes(row)) {
                return "selected-row-color";
            }
            return "";
        },
        handleSelectionChange(val) {
            console.log("选中", val);
            this.multipleSelection = val;
        },
        checkTable(emitData) {
            // emitData.map(p=>{
            // 	p.reconciliationStatus=3;
            // 	p.storeReconciliationStatus=3;
            // })

            this.entityObj.items = [...this.initItems, ...emitData];
        },
        // 主页面进来的 接送对账数据
        initTable(emitData, type) {
            console.log("checkTable:", emitData);
            this.visible = true;
            this.handleType = type;
            this.initItems = emitData.accountReceivingOrderItems;
            this.entityObj.items = emitData.accountReceivingOrderItems;
            this.entityObj.accountDate = [
                emitData.accountStartDate,
                emitData.accountEndDate,
            ];
            this.entityObj.accountFile = emitData.accountFile;
            this.entityObj.storeId = emitData.storeId;
            this.entityObj.store = {
                storeName: emitData.storeName,
                storeId: emitData.storeId,
            };
            this.entityObj.salesAccountID = emitData.salesAccountID;
            this.entityObj.remarks = emitData.remarks;
            this.entityObj.applicantUser = emitData.applicantUser;
            this.entityObj.tel = emitData.tel;
            this.entityObj.purchaseUnityFullName =
                emitData.purchaseUnityFullName;
        },
        resetSearch() {
            this.queryList = {};
        },
        handleSearch() {
            var items = this.initItems;
            if (this.queryList.materialCode) {
                items = items.filter((item) => {
                    return item.materialCode.includes(
                        this.queryList.materialCode
                    );
                });
            }

            if (this.queryList.materialName) {
                items = items.filter((item) => {
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
            }
            if (this.queryList.materialSpecs) {
                items = items.filter((item) => {
                    return item.materialSpecs.includes(
                        this.queryList.materialSpecs
                    );
                });
            }
            if (this.queryList.applyOrderCode) {
                items = items.filter((item) => {
                    return item.applyOrderCode.includes(
                        this.queryList.applyOrderCode
                    );
                });
            }
            this.entityObj.items = items;
            console.log(items);
        },
        // 保存对账单申请
        async isSaveing(type) {
            let modal = {
                ...this.entityObj,
            };
            modal["accountReceivingOrderItems"] = modal.items;
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "receiving-order/updatesaleaccount",
                modal
            );
            if (returnValue.status == 200) {
                if (type == 0) {
                    this.$emit("success");
                    this.visible = false;
                    this.$message.success(returnValue.msg);
                }
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        // 批量对账  未合并代码1-1
        async allSelect() {
            //对账前先保存修改内容
            await this.isSaveing(1);

            if (this.multipleSelection.length < 1) {
                this.$message.error("请选择要对账的数据");
                return;
            }
            let ids = [];
            console.log("allSelect..", this.multipleSelection);
            this.multipleSelection.forEach((item) => {
                ids.push(item.receivingOrderId);
            });
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "receiving-order/account",
                ids
            );
            if (returnValue.status == 200) {
                this.multipleSelection.forEach((item) => {
                    item.reconciliationStatus = "1";
                });
                this.$emit("success");
                this.visible = false;
                this.$message.success(returnValue.msg);
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        // 单条对账 未合并代码1-1
        async opSelect(checkRow, index) {
            //对账前先保存修改内容
            await this.isSaveing(1);
			
            let id = [checkRow.receivingOrderId];
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "receiving-order/account",
                id
            );
            if (returnValue.status == 200) {
                debugger;
                // 建议统一 storeReconciliationStatus与reconciliationStatus
                if (this.orgType === 2) {
                    checkRow.storeReconciliationStatus = "1";
                } else if (this.orgType === 1) {
                    checkRow.reconciliationStatus = "1";
                }
                this.$message.success(returnValue.msg);
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        // 批量选择删除 前端自行操作
        opDelSelect() {
            if (this.multipleSelection.length < 1) {
                this.$message.error("请选择要删除的数据");
                return;
            }
            let ids = [];
            this.multipleSelection.forEach((item) => {
                ids.push(item.receivingOrderId);
            });
            console.log("allSelect..", this.multipleSelection);
            this.entityObj.items = this.entityObj.items.filter(
                (item) => !ids.includes(item.receivingOrderId)
            );
        },
        // 单个删除 前端自行操作
        opDel(row, index) {
            this.entityObj.items.splice(index, 1);
            // let items = this.entityObj.items;
            // let filteredItems = items.filter(item => item.receivingOrderId !== row.receivingOrderId);
            // this.entityObj.items = filteredItems;
        },
        // 前端自行操作 弹窗 对物料的信息进行调整
        opCheck(checkRow, index) {
            switch(checkRow.receivingOrderType){
                case 0:
                    this.dialogUpdatePrice = true;
                    this.$nextTick(() => {
                        this.$refs.updatePriceDialog.setData(checkRow);
                        this.$refs.updatePriceDialog.open("updatePrice");
                    });
                    break;
                default:
                    this.dialogCheck = true;
                    this.$nextTick(() => {
                        console.log("opCheck", checkRow);
                        this.$refs.checkDialog.setData(checkRow);
                        this.$refs.checkDialog.open("Check");
                    });
                    break;
            }
        },
        async orgSelectProcess(rowData) {
            this.entityObj.store = rowData;
            this.entityObj.storeId = rowData.storeId;
        },
        open() {
            this.visible = true;
            this.entityObj.items = [];
        },
        async submitSave() {
            if (!this.entityObj.accountDate) {
                this.$message.error("请选择销售单日期");
                return;
            }
            if (!this.entityObj.storeId) {
                this.$message.error("请选择客户");
                return;
            }
            if (!this.entityObj.items.length > 0) {
                this.$message.error("请选择出库单");
                return;
            }
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "receiving-order/saleaccount",
                this.entityObj
            );
            if (returnValue.status == 200) {
                this.$message.success(returnValue.msg);
                this.$emit("success");
                this.visible = false;
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) =>
                    Number(item[column.property])
                );

                if (column.property == "qty") {
                    var qtySum = 0;
                    this.multipleSelection.map((selectItem) => {
                        qtySum += selectItem.qty;
                    });
                    sums[index] = qtySum;
                }
                if (column.property == "price") {
                    var PriceSum = 0;
                    this.multipleSelection.map((selectItem) => {
                        PriceSum += selectItem.price;
                    });
                    sums[index] = PriceSum;
                }
                if (column.property == "totalAmount") {
                    var totalAmountSum = 0;
                    this.multipleSelection.map((selectItem) => {
                        totalAmountSum += selectItem.totalAmount;
                    });
                    sums[index] = totalAmountSum;
                }
            });
            return sums;
        },
        checkSaveSuccess(data) {
            console.log("chenk", data);
            let item = this.entityObj.items.find(
                (p) => p.receivingOrderId == data.receivingOrderId
            );
            item.price = data.price;
            item.qty = data.qty;
            item.totalAmount = data.price * data.qty;
        },
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        console.log(this.orgType);
    },
};
</script>

<style lang="scss" scoped>
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
//   斑马纹选中颜色
::v-deep .el-table__body .el-table__row--striped.selected-row-color td {
    background-color: #b8dcff !important;
}
::v-deep .el-table {
    --el-table-row-hover-bg-color: #dae8f7;
}

::v-deep .el-table tr:nth-child(2n) {
    background: #f2f2f2;
}
</style>
<style>
.el-table .selected-row-color {
    background-color: #b8dcff !important;
}
.el-table--enable-row-hover .el-table__body tr.selected-row-color:hover > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper .el-table__body tr.selected-row-color.hover-row > td {
    background-color: #b8dcff !important;
}
.el-table__fixed-body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > .el-table__row--striped {
    background-color: #b8dcff !important;
}
</style>
